<?php

namespace App\Services;

use App\Exceptions\AuthException;
use App\Exceptions\FobbidenException;
use App\Models\BlacklistModel;
use App\Models\UserModel;

class BlacklistService extends BaseService
{
    /**
     * 查询黑名单中的用户
     *
     * @param int $userId
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object|null
     */
    public function getBlackListByUserId(int $userId)
    {
        return BlacklistModel::query()
            ->select('id', 'user_id', 'deleted_at')
            ->where('user_id', $userId)
            ->where('deleted_at', 0)
            ->first();
    }

    /**
     * 是否在黑名单中
     *
     * @param int $userId
     * @return bool
     */
    public function ifInBlacklist(int $userId): bool
    {
        return (bool)$this->getBlackListByUserId($userId);
    }

    public function getBlackListByUserIds(array $userIds)
    {
        return BlacklistModel::query()
            ->select('id', 'user_id')
            ->whereIn('user_id', $userIds)
            ->where('deleted_at', 0)
            ->get();
    }

    /**
     * 拉黑用户
     *
     * @param int $user_id
     * @return bool|\Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model
     * @throws AuthException
     * @throws FobbidenException
     */
    public function blockUser(int $user_id)
    {
        $user = auth()->user();
        if (! $user) {
            throw new AuthException('请先登录', 401);
        }

        if ($user->role != UserModel::ROLE_ADMIN) {
            throw new FobbidenException('您无权作此操作', 403);
        }

        $blacklist = $this->getBlackListByUserId($user_id);
        if ($blacklist) {
            $blacklist->deleted_at = time();

            return $blacklist->save();
        } else {
            return BlacklistModel::query()
                ->create([
                    'user_id' => $user_id,
                    'created_at' => time()
                ]);
        }
    }
}
